package com.lanou.service.imp;

import com.lanou.bean.UserBean;
import com.lanou.mapper.RegisterMapper;
import com.lanou.service.RegisterService;
import com.lanou.utils.AjaxResult;
import com.lanou.utils.StrUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class RegisterServiceImp implements RegisterService {


    @Resource
    private RegisterMapper registerMapper;

    @Override
    public void addUser(UserBean userBean) {
        registerMapper.addUser(userBean);
    }

    @Override
    public AjaxResult userRegister(String name, String password, String tel, String address) {

        UserBean user1 = new UserBean();
        user1.setName(name);
        user1.setPassword(password);
        user1.setTel(tel);
        user1.setAddress(address);

        AjaxResult result = new AjaxResult();

        if (!userArgs(user1)) {

            result.setCode("0");// 0代表注册失败
            result.setMsg("注册失败, 请检查参数");

            return result;
        }

        if (userExist(name)) {

            result.setCode("0");// 0代表注册失败
            result.setMsg("注册失败, 请重新设置用户名");

            return result;
        } else {
            addUser(user1);

            result.setCode("1");
            result.setMsg("注册成功");
            result.setData(user1);

            return result;
        }
    }

    @Override
    public boolean userExist(String username) {

        return registerMapper.userExist(username) > 0;
    }

    // 判断参数是否合法
    private boolean userArgs(UserBean user) {

        // 用户名和密码不能为空
        if (StrUtils.isNull(user.getName()) ||
                StrUtils.isNull(user.getPassword())) {
            return false;
        }

        // 电话号码必须合法
        if (!StrUtils.isPhoneNumberRight(user.getTel())) {
            return false;
        }

        return true;

        // 97~102行也可以如下替换
//        return StrUtils.isPhoneNumberRight(user.getTel());
    }


}
